﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    internal class PDAStocktakingRepository : BaseRepository<TStackingStorage>, IPDAStocktakingRepository
    {
        public PDAStocktakingRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 获取所有盘点单号
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllStocktaking()
        {
            List<string> OrderSns = new List<string>();
            var StocktakingList = Context.TStocktakingOrders.Where(x => x.Status == 1).ToList();
            foreach (var item in StocktakingList)
            {
                string OrderSn = item.OrderSn;
                OrderSns.Add(OrderSn);
            }
            return OrderSns;
        }

        /// <summary>
        /// 根据OrderSn获取盘点单
        /// </summary>
        /// <returns></returns>
        public List<StocktakingDto> GetStocktakingOrdersByOrderSn(string OrderSn)
        {
            var StocktakingList = Context.TStocktakingOrders.Where(x => x.OrderSn == OrderSn).ToList();
            List<StocktakingDto> stocktakingDtos = new List<StocktakingDto>();
            foreach (var item in StocktakingList)
            {
                StocktakingDto stocktakingDto = new StocktakingDto();
                stocktakingDto.Id = item.Id;
                stocktakingDto.Name = item.Name;
                stocktakingDto.OrderSn = item.OrderSn;
                stocktakingDto.WarehouseId = item.WarehouseId;
                stocktakingDto.WarehouseCode = item.WarehouseCode;
                stocktakingDto.WarehouseName = item.WarehouseName;
                stocktakingDto.BillType = item.BillType;
                stocktakingDto.Status = item.Status;
                stocktakingDto.BatchNo = item.BatchNo;
                stocktakingDto.PlanType = item.PlanType;
                stocktakingDto.StocktakeWay = item.StocktakeWay;
                stocktakingDto.CellCount = item.CellCount;
                stocktakingDto.FinishedCount = item.FinishedCount;
                stocktakingDto.LoopTimes = item.LoopTimes;
                stocktakingDto.PriorityLevel = item.PriorityLevel;
                stocktakingDto.Remark = item.Remark;
                var childList = Context.TStocktakingOrderDetails.Where(x => x.OrderSn == item.OrderSn).ToList();
                foreach (var child in childList)
                {
                    StocktakingDtoChild stocktakingDtoChild = new StocktakingDtoChild();
                    stocktakingDtoChild.Id = child.Id;
                    stocktakingDtoChild.OrderId = child.OrderId;
                    stocktakingDtoChild.OrderSn = child.OrderSn;
                    stocktakingDtoChild.CellId = child.CellId;
                    stocktakingDtoChild.CellCode = child.CellCode;
                    stocktakingDtoChild.LocationName = child.LocationName;
                    stocktakingDtoChild.CellDepthIndex = child.CellDepthIndex;
                    stocktakingDtoChild.PalletBarcode = child.PalletBarcode;
                    //stocktakingDtoChild.ExpectedStationIds = child.ExpectedStationIds;
                    stocktakingDtoChild.Status = child.Status;
                    stocktakingDtoChild.CreateDate = child.CreateDate;
                    stocktakingDtoChild.MaterialId = child.MaterialId;
                    stocktakingDtoChild.MaterialCode = child.MaterialCode;
                    stocktakingDtoChild.MaterialName = child.MaterialName;
                    stocktakingDtoChild.HasSkuDetail = child.HasSkuDetail;
                    stocktakingDtoChild.Qty = child.Qty;
                    stocktakingDtoChild.ContentQty = child.Qty;
                    stocktakingDtoChild.QualityState = child.QualityState;
                    stocktakingDtoChild.BatchNo = child.BatchNo;
                    stocktakingDtoChild.SmallBatchNo = child.SmallBatchNo;
                    stocktakingDtoChild.OwnerId = child.OwnerId;
                    stocktakingDtoChild.OwnerName = child.OwnerName;
                    //stocktakingDtoChild.ExpireDate = child.ExpireDate;
                    //stocktakingDtoChild.ProductDate = child.ProductDate;
                    //stocktakingDtoChild.SupplierId  = child.SupplierId;
                    //stocktakingDtoChild.SupplierName = child.SupplierName;
                    //stocktakingDtoChild.MaterialTypeId = child.MaterialTypeId;
                    //stocktakingDtoChild.MaterialTypeName = child.MaterialTypeName;
                    //stocktakingDtoChild.Step = child.Step;
                    //stocktakingDtoChild.IsNeedMove = child.IsNeedMove;
                    stocktakingDtoChild.InventoryId = child.InventoryId;
                    stocktakingDtoChild.WarehouseId = child.WarehouseId;
                    stocktakingDto.child.Add(stocktakingDtoChild);
                }
                stocktakingDtos.Add(stocktakingDto);
            }

            return stocktakingDtos;
        }

        public bool AddStocktakingResult(TStocktakeResultRecorddtofengzhuang dto, out string message)
        {
            using (var reader = Context.Database.BeginTransaction())
            {
                try
                {
                    foreach (var item in dto.Items)
                    {

                        //if (string.IsNullOrEmpty(item.pandiandingdan))
                        //{
                        //    message = "返回数据没有值";
                        //    return false;
                        //}
                        //if (item.cellcode == null)
                        //{
                        //    message = "货位没有值";
                        //    return false;
                        //}
                        var stocktakingList = Context.TStocktakingOrders.Where(x => x.OrderSn == dto.OrderSn).ToList();
                        if (stocktakingList.Count() <= 0)
                        {
                            message = "暂未查询到盘点单号：" + dto.OrderSn;
                            return false;
                        }
                        var stocktakingDetailList = Context.TStocktakingOrderDetails.Where(x => x.OrderSn == stocktakingList.First().OrderSn);
                        if (stocktakingDetailList.Count() <= 0)
                        {
                            message = "暂未查询到盘点单明细：" + dto.OrderSn;
                            return false;
                        }
                        stocktakingList.First().Status = 4;
                        var UpdStocktaking = Context.TStocktakingOrders.Update(stocktakingList.First());
                        foreach (var stocktaking in stocktakingDetailList)
                        {
                            stocktaking.Status = 4;
                            var UpdStocktakingDetail = Context.TStocktakingOrderDetails.Update(stocktaking);
                        }
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "盘点单" + stocktakingList.First().OrderSn + "状态更新失败";
                            return false;
                        }
                        List<TStocktakeResultRecord> recordList = new List<TStocktakeResultRecord>();

                        TStocktakeResultRecord xianshi = new TStocktakeResultRecord();
                        xianshi.OrderId = item.OrderId;
                        xianshi.OrderSn = dto.OrderSn;
                        xianshi.AreaId = item.AreaId;
                        xianshi.AreaName = item.AreaName;
                        xianshi.MaterialId = item.MaterialId;
                        var materialList = Context.TMaterial.Where(x => x.Id == item.MaterialId).ToList();
                        if (materialList.Count <= 0)
                        {
                            message = "未查询到物料Id为" + item.MaterialId + "的相关信息";
                            return false;
                        }
                        xianshi.MaterialName = materialList.First().Name;
                        xianshi.CellCode = item.cellcode;
                        xianshi.BillTypeName = dto.Imgagesrc;
                        xianshi.CellId = item.CellId;
                        xianshi.CellDepthIndex = item.CellDepthIndex;
                        xianshi.CreateUserId = item.CreateUserId;
                        xianshi.OriginalQty = item.qty;//库存数量
                        xianshi.CountQty = item.ContentQty;//盘点后数量
                        if (item.ContentQty == item.qty)//盘平
                        {
                            xianshi.Status = 1;
                        }
                        else if (item.ContentQty > item.qty)//盘盈
                        {
                            xianshi.Status = 2;
                        }
                        else if (item.ContentQty < item.qty)
                        {
                            xianshi.Status = 3;
                        }
                        xianshi.CreateDate = DateTime.Now;
                        xianshi.Remark = item.Remark;
                        xianshi.WarehouseId = item.WarehouseId;
                        xianshi.ScanBarcode = stocktakingList.First().BatchNo;
                        var warehouseList = Context.TWarehouses.Where(x => x.Id == item.WarehouseId).ToList();
                        if (warehouseList.Count() <= 0)
                        {
                            message = "未查询到库房Id为：" + item.WarehouseId + "的相关信息！";
                            return false;
                        }
                        xianshi.WarehouseName = warehouseList.First().Name;
                        xianshi.CreateUserName = dto.CreateName;
                        xianshi.IsHandle = 1;
                        xianshi.ScanBarcode = item.supplierName;
                        //if (item.qualityStatus == 1)
                        //{
                        //    item.StatusNam = "盘平";
                        //}
                        //else if (item.qualityStatus == 2)
                        //{
                        //    item.StatusNam = "盘盈";
                        //}
                        //else if (item.qualityStatus == 3)
                        //{
                        //    item.StatusNam = "盘亏";
                        //}
                        recordList.Add(xianshi);

                        Context.TStocktakeResultRecords.AddRange(recordList);
                        Context.SaveChanges();

                    }
                    message = "添加成功" + dto.Items.Count;
                    reader.Commit();
                    return true;
                }
                catch (Exception)
                {
                    reader.Rollback();
                    throw new Exception();
                }
            }
        }
    }
}
